from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.automap import automap_base

dbHost = 'mysql+pymysql://root:123456@127.0.0.1:3306/hzrag'
myengine = create_engine(
    dbHost,
    echo=True,  # 是否打印SQL
    pool_size=10,  # 连接池的大小，指定同时在连接池中保持的数据库连接数，默认:5
    max_overflow=20,  # 超出连接池大小的连接数，超过这个数量的连接将被丢弃,默认: 5
)

from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
 
# 创建会话工厂
mySession = sessionmaker(bind=myengine)
myBase = automap_base() 
myBase.prepare(myengine, reflect=True)
 

@contextmanager
def getMySession(autoCommitByExit=True):
    """使用上下文管理资源关闭"""
    session = Session()
    try:
        yield session
        # 退出时，是否自动提交
        if autoCommitByExit:
            session.commit()
    except Exception as e:
        session.rollback()
        raise e
    finally:
        session.close()

def myeng():
    return engine;

def mydbkey():
    session = mySession()  
    return myengine ,session,myBase,myBase.classes